import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_location_marker/flutter_map_location_marker.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'package:situation/app/theme/gaps.dart';
import 'package:situation/data/store/config_store.dart';
import 'package:situation/widgets/intercom/intercom_call.dart';
import 'package:situation/widgets/map/layer/imaging_layer.dart';
import 'package:situation/widgets/map/map_dropdown.dart';
import 'package:situation/widgets/map/map_track.dart';
import 'package:situation/widgets/map/my_mark_layer.dart';
import 'package:situation/widgets/map/tool/area_measure_tool.dart';
import 'package:situation/widgets/map/tool/distance_measure_tool.dart';
import 'package:situation/widgets/map/tool/map_line_draw.dart';
import 'package:situation/widgets/map/tool/map_point_draw.dart';
import 'package:situation/widgets/map/tool/map_polygon_draw.dart';
import 'package:situation/widgets/mk_load_image.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'controller.dart';
import 'state.dart';

class HomeIndexPage extends StatefulWidget {
  const HomeIndexPage({Key? key}) : super(key: key);

  @override
  State<HomeIndexPage> createState() => _HomeIndexPageState();
}

class _HomeIndexPageState extends State<HomeIndexPage> {
  final HomeIndexController controller = Get.put(HomeIndexController());
  final HomeIndexState state = Get.find<HomeIndexController>().state;

  late AlignOnUpdate _alignPositionOnUpdate;
  late final StreamController<double?> _alignPositionStreamController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _alignPositionOnUpdate = AlignOnUpdate.always;
    _alignPositionStreamController = StreamController<double?>();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      body: Obx(
        () => FlutterMap(
          mapController: controller.animatedMapController.mapController,
          options: MapOptions(
            initialCenter: state.latlon,
            initialZoom: 17,
            backgroundColor: Colors.black87,
            keepAlive: false,
            onTap: controller.mapOnTap,
          ),
          children: [
            if (state.mapType == 'yxt') ...[...ImagingLayer.getImagingLayer()],
            if (state.mapType == 'dzt') ...[...ImagingLayer.getDztLayer()],

            //  ===========  周边队员  ===========
            Obx(() => _buildRoundPartners()),
            //  ===========  周边队员  ===========

            // 右侧底图切换
            Align(
              alignment: Alignment.bottomRight,
              child: GestureDetector(
                onTap: () {
                  controller.switchMap();
                },
                child: Container(
                  margin: EdgeInsets.only(right: 16, bottom: Get.height * 0.8),
                  width: 40,
                  height: 40,
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.lightBlue,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(
                    Icons.swap_horizontal_circle,
                    color: Colors.white,
                    size: 20,
                  ),
                ),
              ),
            ),

            //  ===========  定位  ===========
            CurrentLocationLayer(
              alignPositionStream: _alignPositionStreamController.stream,
              alignPositionOnUpdate: _alignPositionOnUpdate,
            ),
            Align(
              alignment: Alignment.bottomRight,
              child: GestureDetector(
                onTap: () {
                  setState(() => _alignPositionOnUpdate = AlignOnUpdate.always);
                  _alignPositionStreamController.add(18);
                },
                child: Container(
                  margin: EdgeInsets.only(right: 16, bottom: 80),
                  width: 40,
                  height: 40,
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.lightBlue,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(Icons.my_location, color: Colors.white, size: 20),
                ),
              ),
            ),
            //  ===========  定位  ===========

            //  ===========  对讲  ===========
            Align(
              alignment: Alignment.bottomRight,
              child: Container(
                margin: EdgeInsets.only(right: 16, bottom: 160),
                width: 40,
                height: 40,
                padding: EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.lightBlue,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: IntercomCall(),
              ),
            ),
            //  ===========  对讲  ===========

             //  ===========  轨迹  ===========
            MapTrack(),
            //  ===========  轨迹  ===========






            _buildMapTopMenu(),
            //  ===========  点绘制  ===========
            MapPointDraw(
              key: MapPointDraw.stateKey,
              onSave: controller.onSinglePointSave,
              onClose: controller.resetEventTool,
            ),
            //  ===========  点绘制  ===========
            //  ===========  线绘制  ===========
            MapLineDraw(
              key: MapLineDraw.stateKey,
              onSave: controller.onLineSave,
              lineColor: Colors.blue,
            ),
            //  ===========  线绘制  ===========
            //  ===========  面绘制  ===========
            MapPolygonDraw(
              key: MapPolygonDraw.stateKey,
              onSave: controller.onAreaSave,
            ),
            //  ===========  面绘制  ===========
            //  ===========  距离测算  ===========
            DistanceMeasureTool(
              key: DistanceMeasureTool.stateKey,
              onClose: controller.resetEventTool,
            ),
            //  ===========  距离测算  ===========
            //  ===========  面积测算  ===========
            AreaMeasureTool(
              key: AreaMeasureTool.stateKey,
              onClose: controller.resetEventTool,
            ),
            //  ===========  面积测算  ===========


            Obx(()=>MyMarkLayer(dataList: state.myMarkList))
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: 0,
        onTap: controller.changeTab,
        backgroundColor: Colors.black.withAlpha(60),
        type: BottomNavigationBarType.fixed,
        selectedItemColor: Colors.white,
        unselectedItemColor: Colors.white,
        selectedLabelStyle: TextStyle(color: Colors.white, fontSize: 12),
        unselectedLabelStyle: TextStyle(color: Colors.white, fontSize: 12),
        items: [
          BottomNavigationBarItem(
            icon: SvgPicture.asset("assets/svg/map.svg", width: 20, height: 20),
            label: '地图',
          ),
          BottomNavigationBarItem(
            icon: SvgPicture.asset(
              "assets/svg/intercom.svg",
              width: 20,
              height: 20,
            ),
            label: '通信',
          ),
          BottomNavigationBarItem(
            icon: SvgPicture.asset(
              "assets/svg/intell.svg",
              width: 20,
              height: 20,
            ),
            label: '信息采集',
          ),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'),
        ],
      ),
    );
  }

  @override
  void dispose() {
    Get.delete<HomeIndexController>();
    _alignPositionStreamController.close();
    super.dispose();
  }

  _buildRoundPartners() {
    return MarkerLayer(
      markers: [
        ...state.aroundPoints.map((e) {
          return Marker(
            alignment: Alignment.topCenter,
            width: 60,
            height: 88,
            point: LatLng(double.parse(e['lat']), double.parse(e['lon'])),
            child: Tooltip(
              message: "${e['name']}",
              child: GestureDetector(
                onTap: () {
                  controller.toChat(e);
                },
                child: Container(
                  child: Column(
                    children: [
                      Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: Colors.blue, width: 2),
                          borderRadius: BorderRadius.all(Radius.circular(80)),
                        ),
                        child: Stack(
                          children: [
                            Container(
                              child: MkLoadImage(
                                ConfigStore.to.baseFileUrl +
                                    "/" +
                                    e['headImgUrl'],
                                width: 40,
                                height: 38,
                              ),
                              clipBehavior: Clip.antiAliasWithSaveLayer,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(
                                  Radius.circular(40),
                                ),
                              ),
                            ),
                            Positioned(
                              child: Container(
                                width: 10,
                                height: 10,
                                decoration: BoxDecoration(
                                  color:
                                      e['online'] == "0"
                                          ? Colors.greenAccent
                                          : Colors.redAccent,
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(6),
                                  ),
                                ),
                              ),
                              right: 0,
                              bottom: 0,
                            ),
                          ],
                        ),
                      ),
                      Gaps.vGap4,
                      Container(
                        padding: EdgeInsets.all(2),
                        decoration: BoxDecoration(
                          color: Colors.white.withAlpha(120),
                        ),
                        child: Text(
                          "${e['name']}",
                          style: TextStyle(fontSize: 12),
                        ),
                      ),
                      Icon(
                        Icons.arrow_drop_down,
                        color: Colors.yellow,
                        size: 24,
                      ),
                    ],
                  ),
                ),
              ),
            ),
          );
        }),
      ],
    );
  }

  // 顶部按钮
  _buildMapTopMenu() {
    return Align(
      alignment: Alignment.topCenter,
      child: MapDropdown(
        onPointDraw: controller.drawPoint,
        onLineDraw: controller.drawLine,
        onAreaDraw: controller.drawArea,
        onMeasureDistance: controller.sumDistance,
        onMeasureArea: controller.sumArea,
        onClean: controller.drawClear,
        handleMyMark: controller.handleMyMark,
      ),
    );
  }
}
